<template>
  <echarts
    ref="chart"
    v-loading="loading"
    :theme="theme"
    :auto-resize="true"
    :init-options="initOption"
    :options="option"
    element-loading-text="Loading..."
    class="chart"
    @click="handleChartClick"
  />
</template>
<script>
import { getPlotMapConfig } from '../config/plot-map-config'
import chinaMap from '../../map/china'
export default {
  name: 'PlotMap',
  props: {
    loading: {
      type: Boolean,
      default: true
    },
    option: {
      type: Object,
      default() {
        return getPlotMapConfig().option
      }
    },
    apiData: {
      type: Array,
      default() {
        return {}
      }
    },
    theme: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      chartType: 'plotMap',
      initOption: getPlotMapConfig().option,
      geoCoordMap: {}
    }
  },
  watch: {
    apiData: function() {
      this.setData()
    }
  },
  async mounted() {
    const chart = this.$refs.chart
    this.$emit('init', {
      chart: chart
    })
    // 获取地图数据
    var geoMap = {}
    chinaMap.features.forEach(function(v) {
      // 名称 + 经纬度
      geoMap[v.properties.name] = v.properties.cp
    })
    this.geoCoordMap = geoMap
  },
  methods: {
    handleChartClick(param) {
    },
    setData() {
      const _data = this.apiData
      this.option.series[0].data = this.convertData(_data)
      this.option.series[1].data = _data
      var top3Data = JSON.parse(JSON.stringify(_data))
      if (top3Data.length >= 3) {
        var data = top3Data.sort(function(a, b) {
          return b.value - a.value
        })
        this.option.visualMap.max = data[0].value
        this.option.series[3].data = this.convertData(data.slice(0, 3))
      }
    },
    convertData(data) {
      const geoMap = this.geoCoordMap
      var res = []
      for (var i = 0; i < data.length; i++) {
        var geoCoord = geoMap[data[i].name]
        if (geoCoord) {
          res.push({
            name: data[i].name,
            value: geoCoord.concat(data[i].value)
          })
        }
      }
      return res
    }
  }
}
</script>
